/*
 * 文 件 名:  SecurityConfig
 * 版    权:
 * 描    述:  <描述>
 * 修 改 人:  redName
 * 修改时间:  2022/4/30
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.zj003.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zj003.common.constant.MimeType;
import com.zj003.common.domain.result.Result;
import com.zj003.framework.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * <功能详细描述>
 * spring security配置
 *
 * @author ReaName
 * @version [版本号, 2022/4/30]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    private final UserDetailsService userDetailsService;
    private final UserDetailsPasswordService userDetailsPasswordService;

    private final JwtAuthenticationFilter jwtAuthenticationFilter;


    private final ObjectMapper objectMapper;

    private final   CorsConfigurationSource configurationSource;


    /**
     * 强散列哈希加密实现
     *
     * @return org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
     * @author RedName
     * {@code @date} 2022/4/30 3:30
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份管理器
     *
     * @return org.springframework.security.authentication.AuthenticationManager
     * @author RedName
     * {@code @date} 2022/5/6 4:19
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 参数配置
     * <p>
     * anyRequest          |   匹配所有请求路径
     * <p>
     * access              |   SpringEl表达式结果为true时可以访问
     * <p>
     * anonymous           |   匿名可以访问
     * <p>
     * denyAll             |   用户不能访问
     * <p>
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * <p>
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * <p>
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * <p>
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * <p>
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * <p>
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * <p>
     * permitAll           |   用户可以任意访问
     * <p>
     * rememberMe          |   允许通过remember-me登录的用户访问
     * <p>
     * authenticated       |   用户登录后可访问
     *
     * @param http:
     * @author RedName
     * {@code @date} 2022/4/30 3:32
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {

        //session失效
        http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        //所有请求都要认证
        http.authorizeRequests(request -> request.antMatchers("/login").permitAll().anyRequest().authenticated());
        //http.authorizeRequests(request -> request.anyRequest().authenticated());
        http.httpBasic(AbstractHttpConfigurer::disable);
        // 配置跨域
        http.cors(cors -> cors.configurationSource(configurationSource));

        http.csrf(AbstractHttpConfigurer::disable);
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling(exception -> exception.authenticationEntryPoint(authenticationEntryPoint()).accessDeniedHandler(accessDeniedHandler()));
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                //用户服务
                .userDetailsService(userDetailsService)
                //密码服务
                .userDetailsPasswordManager(userDetailsPasswordService)
                //加密类型
                .passwordEncoder(bCryptPasswordEncoder());

    }

    //@Override
    //public void configure(WebSecurity web) throws Exception {
    //    web.ignoring().mvcMatchers("/login");
    //}


    private AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, e) -> {
            response.setContentType(MimeType.APPLICATION_JSON_CHARSET);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter outputStream = response.getWriter();
            Result result = Result.error("请先登录");
            outputStream.println(objectMapper.writeValueAsString(result));
        };
    }

    private AccessDeniedHandler accessDeniedHandler() {
        return (request, response, e) -> {
            response.setContentType(MimeType.APPLICATION_JSON_CHARSET);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            PrintWriter outputStream = response.getWriter();
            Result result = Result.error(e.getMessage());
            outputStream.println(objectMapper.writeValueAsString(result));
        };
    }
}
